package logic

import (
	"common/model"
	"context"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
	order "order_server/proto"
)

// OrderDetail 获取订单详情
func (o *OrderServer) OrderDetail(ctx context.Context, req *order.OrderDetailRequest) (*order.OrderDetailResponse, error) {
	// 1. 查询主订单信息
	masterOrder, err := model.GetOrderCatInfo(req.OrderId)
	if err != nil {
		return nil, status.Errorf(codes.NotFound, "订单不存在: %v", err)
	}

	// 2. 构建基本响应
	response := &order.OrderDetailResponse{
		Master: &order.OrderMasterInfo{
			Id:            masterOrder.Id,
			OrderNo:       masterOrder.OrderNo,
			UserId:        masterOrder.UserId,
			ProductId:     masterOrder.ProductId,
			OrderType:     masterOrder.OrderType,
			OriginalPrice: masterOrder.OriginalPrice,
			ActualPrice:   masterOrder.ActualPrice,
			Quantity:      masterOrder.Quantity,
			Status:        masterOrder.Status,
			PaymentTime:   masterOrder.PaymentTime.Format("2006-01-02 15:04:05"),
			CreatedAt:     masterOrder.CreatedAt.Format("2006-01-02 15:04:05"),
			UpdatedAt:     masterOrder.UpdatedAt.Format("2006-01-02 15:04:05"),
		},
	}

	// 3. 获取商品信息（需要调用product服务）
	productInfo, err := model.GetProductInfo(masterOrder.ProductId)
	if err == nil && productInfo != nil {
		response.ProductName = productInfo.StoreName
		response.ProductImage = productInfo.Image
	}

	// 4. 根据订单类型获取详细信息
	switch masterOrder.OrderType {
	case 4: // 秒杀订单
		seckillOrder, err := model.GetSeckillOrderByOrderId(req.OrderId)
		if err == nil && seckillOrder != nil {
			response.OrderDetail = &order.OrderDetailResponse_Seckill{
				Seckill: &order.OrderSeckillInfo{
					Id:            seckillOrder.Id,
					ActivityId:    seckillOrder.ActivityId,
					SeckillPrice:  float64(seckillOrder.SeckillPrice),
					OriginalPrice: float64(seckillOrder.OriginalPrice),
					Status:        seckillOrder.Status,
				},
			}
		}
	case 3: // 砍价订单
		bargainOrder, err := model.GetOrderBargainInfo(req.OrderId)
		if err == nil && bargainOrder != nil {
			response.OrderDetail = &order.OrderDetailResponse_Bargain{
				Bargain: &order.OrderBargainInfo{
					Id:           bargainOrder.Id,
					ActivityId:   bargainOrder.ActivityId,
					CurrentPrice: float64(bargainOrder.CurrentPrice),
					CurrentCuts:  bargainOrder.CurrentCuts,
					Status:       bargainOrder.Status,
					ExpireTime:   bargainOrder.ExpireTime.Format("2006-01-02 15:04:05"),
				},
			}
		}
		// 普通订单不需要额外处理
	}

	return response, nil
}
